//获取应用实例
const app = getApp()

Page({

  /**
   * 页面的初始数据
   */
  data: {
    provinceIndex:0,
    cityIndex: 0,
    schoolIndex: 0,
    provinces:"",
    cities: ['请选择城市'],
    schools: ['请选择学校'],

    motto: 'Hello World',
    userInfo: "",
    hasUserInfo: app.globalData.hasUserInfo,
    canIUse: wx.canIUse('button.open-type.getUserInfo'),

    teams:""
  },

  findSchoolsByCityName: function (name) {
    wx.request({
      url: 'http://' + app.globalData.ip +'/location/findSchoolsByCity',
      data: { 'cityName': name },
      success: (res) => {
        this.setData({
          schools: res.data['schools'],
          schoolIndex: 0
        })
      }
    })
  },

  /*下拉框改变时引起的change事件*/ 
  changeProvince:function(e){
    this.setData({
      provinceIndex:e.detail.value
    })
    var provinceName = this.data.provinces[this.data.provinceIndex]
    if (provinceName == '北京' || provinceName == '上海' || provinceName == '天津' || provinceName == '重庆') {
      this.setData({
        cities: [provinceName + '市'],
        cityIndex: 0,
        schoolIndex: 0,
      })
      this.findSchoolsByCityName(provinceName + '市')
    } else if (provinceName == '香港' || provinceName == '澳门' || provinceName == '台湾') {
      this.setData({
        cities: [],
        schools: [],
        cityIndex: 0,
        schoolIndex: 0
      })
    } else {
      wx.request({
        url: 'http://' + app.globalData.ip +'/location/findCitiesByProvince',
        data: { 'provinceName': this.data.provinces[this.data.provinceIndex] },
        success: (res) => {
          this.setData({
            cities: res.data['cities'],
            cityIndex: 0,
            schoolIndex: 0
          })
        }
      })
    }
    this.getTeamsByLocation()
  },
  changeCity: function (e) {
    this.setData({
      cityIndex: e.detail.value
    })
    this.findSchoolsByCityName(this.data.cities[this.data.cityIndex])
    this.getTeamsByLocation()
  },
  changeSchool: function (e) {
    this.setData({
      schoolIndex: e.detail.value
    })
    this.getTeamsByLocation()
  },
  getTeamsByLocation:function(){
    var pindex = this.data.provinceIndex
    var cindex = this.data.cityIndex
    var sindex = this.data.schoolIndex
    var myData ={}
    myData['provinceIndex'] = pindex
    myData['provinceName'] = this.data.provinces[pindex]
    myData['cityIndex'] = cindex
    myData['cityName'] = this.data.cities[cindex]
    myData['schoolIndex'] = sindex
    myData['schoolName'] = this.data.schools[sindex]
    var userid = app.globalData.hasUserInfo ? app.globalData.userInfo.openId:""
    wx.request({
      url: 'http://' + app.globalData.ip +'/team/getTeamsByLocation',
      data: {userID:userid, "location": JSON.stringify(myData)},
      success:(res)=>{
        console.log(res)
        if(res.data.msg==1){
          if (res.data.teams != 0) {
            var t = res.data.teams
            for (var i = 0; i < t.length; ++i) {
              var d = new Date(t[i]['createTime'])
              t[i]['createTime'] = d.getFullYear() + '.' + d.getMonth() + '.' + d.getDate()
            }
            this.setData({
              teams: t
            })
          } else {
            this.setData({
              teams: []
            })
          }
        }
        
        
      }
    })
  },
  
  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    this.setData({
      provinces: app.globalData.provinces,
      userInfo:app.globalData.userInfo
    })
    this.getTeamsWithoutUserID()
    
    var that = this
    if(app.globalData.userInfo){
      var x = setTimeout(function () {
        that.getTeams() //这里onload可能会执行较快导致getTeams里的openid没获取到
      }, 2000)  
    }
    var x = setTimeout(function () {
      that.setData({
        provinces: app.globalData.provinces
      })
    }, 2000) 
   
  },
  lookDetail:function(e){
    var index = e.currentTarget.dataset.teamindex
    app.globalData.team = this.data.teams[index]
    app.globalData.teamID = this.data.teams[index].teamID
    wx.navigateTo({
      url: '../teamDetail/teamDetail',
    })
  },
  /**点击收藏功能 */
  like:function(e){

    if(app.globalData.hasUserInfo){
      //用户授权过了
      var index = e.currentTarget.dataset.idx
      var teamID = e.currentTarget.dataset.teamid
      var that = this
      var mylike = "teams[" + index + "].like"
      if (this.data.teams[index].like == true) {
        //原先为true表示收藏，则点击时表示取消收藏     
        /**向后端发送请求 取消当前的收藏 */
        wx.request({
          url: 'http://' + app.globalData.ip +'/like/cancleLike',
          data: { userid: app.globalData.userInfo.openId, teamid: teamID },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          success: function (res) {
            if (res.data.msg == 1) {
              wx.showToast({
                title: '取消收藏',
              })
              that.setData({
                [mylike]: false
              })
            } else {
              wx.showModal({
                content: '服务端取消收藏失败',
              })
            }
          },
          fail: function () {
            wx.showModal({
              content: '取消收藏失败',
            })
          }
        })
      } else {
        /**向后端发送请求将当前的收藏 */
        wx.request({
          url: 'http://' + app.globalData.ip +'/like/addLike',
          data: { userid: app.globalData.userInfo.openId, teamid: teamID },
          header: {
            'content-type': 'application/x-www-form-urlencoded'
          },
          method: 'POST',
          success: function (res) {
            if (res.data.msg == 1) {
              wx.showToast({
                title: '收藏成功',
              })
              that.setData({
                [mylike]: true
              })
            } else {
              wx.showModal({
                content: '服务端收藏失败'
              })
            }
          },
          fail: function () {
            wx.showModal({
              content: '收藏失败'
            })
          }
        })
      }

    }else{
      //用户未授权
      wx.showModal({
        content: '请前往授权',
        success:(res)=>{
          if(res.confirm){
            wx.navigateTo({
              url: '../index/index',
            })
          }
        }
      })
    }
    
    
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },
  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {
    this.setData({
      provinces: app.globalData.provinces,
      userInfo: app.globalData.userInfo
    })
    this.getTeamsByLocation();
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
  },

  /** 显示的组队信息可能不会有用户的点赞 */
  getTeamsWithoutUserID: function () {
    wx.request({
      url: 'http://' + app.globalData.ip +'/team/getTeamsWithoutUserID',
      success:(res)=>{
        if(res.data.msg==1){
          var Teams = res.data.teams
          for (var i = 0; i < Teams.length; ++i) {
            var d = new Date(Teams[i]['createTime'])
            Teams[i]['createTime'] = d.getFullYear() + '.' + d.getMonth() + '.' + d.getDate()
          }
          this.setData({
            teams: Teams
          })
          app.globalData.teams = Teams
        }else{
          wx.showModal({
            content: '服务器出错',
          })
        }
      },
      fail: function () {
        wx.showModal({
          content: '前端出错',
        })
      }
    })
  },
  getTeams: function () {
    wx.request({
      url: 'http://' + app.globalData.ip +'/team/getTeams',
      data:{userid:app.globalData.userInfo.openId},
      header: {
        'content-type': 'application/x-www-form-urlencoded'
      },
      method:'POST',
      success: (res) => {
        var myteams = res.data.teams
        for (var i = 0; i < myteams.length; ++i) {
          var d = new Date(myteams[i]['createTime'])
          myteams[i]['createTime'] = d.getFullYear() + '.' + d.getMonth() + '.' + d.getDate()
        }        
        this.setData({
          teams: myteams
        })
        app.globalData.teams = myteams
      },
      fail:()=>{
        this.setData({
          teams: "获取组队信息失败"
        })
      }
    })
  },
  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },



  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  },
  
})